package com.xb.cloud.search.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SearcherClient;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.search.Config;
import com.aliyun.opensearch.sdk.generated.search.Order;
import com.aliyun.opensearch.sdk.generated.search.SearchFormat;
import com.aliyun.opensearch.sdk.generated.search.SearchParams;
import com.aliyun.opensearch.sdk.generated.search.Sort;
import com.aliyun.opensearch.sdk.generated.search.SortField;
import com.aliyun.opensearch.sdk.generated.search.general.SearchResult;
import com.aliyun.opensearch.search.SearchParamsBuilder;
import com.xb.cloud.common.JsonUtils;
import com.xb.cloud.common.util.StringUtils;
import com.xb.cloud.product.search.service.client.SearchService;
import com.xb.cloud.product.search.service.client.bo.SearchRequestBo;
import com.xb.cloud.product.search.service.client.bo.SearchResultBo;
import com.xb.cloud.product.search.service.client.bo.SearchResultSKUBo;
import com.xb.cloud.product.search.service.client.bo.SearchResultShopBo;
import com.xb.cloud.product.service.business.model.SearchALiResultBo;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;

@Service
public class SearchServiceImpl implements SearchService {
	private String appName = "xb_cloud_hx";
	private String tableName = "search_table_sku_shop";
	private String accesskey = "LTAIoKu0VMKqIjS7";
	private String secret = "iyEMrQdF1XtKvPTV45BvgSoiVKk77F";
	private String host = "http://opensearch-cn-hangzhou.aliyuncs.com";
	// 创建并构造OpenSearch对象
	private OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
	// 创建OpenSearchClient对象，并以OpenSearch对象作为构造参数
	private OpenSearchClient serviceClient = new OpenSearchClient(openSearch);

	private SearcherClient searcherClient = new SearcherClient(serviceClient);

	@Override
	public ServiceReturnInfo searchByKeyword(SearchRequestBo requestBo) {
		// TODO Auto-generated method stub
		SearchResultBo resultBo = new SearchResultBo();
		if ( requestBo.getPageNum() == 0) {
			/**
			 * 此逻辑是新查询,需要先查询shop是否存在
			 */
			
			List<SearchResultShopBo> shopResultList = getShopResult(requestBo);
			resultBo.setShopBoList(shopResultList);
			
			
		}
		List<SearchResultSKUBo> skuResultList = getSkuResult(requestBo);
		resultBo.setSkuBoList(skuResultList);
		
		
		return ServiceReturnUtils.success(resultBo);

	}

	private List<SearchResultSKUBo> getSkuResult(SearchRequestBo requestBo) {
		// 获取shop信息
		Config config = new Config(Lists.newArrayList(appName));
		config.setStart(requestBo.getPageNum());
		config.setHits(requestBo.getPageSize());
		// 设置返回格式为fulljson格式
		config.setSearchFormat(SearchFormat.JSON);
		// 创建参数对象
		SearchParams searchParams = new SearchParams(config);
		// 指定搜索的关键词，这里要指定在哪个索引上搜索，如果不指定的话默认在使用“default”索引（索引字段名称是您在您的数据结构中的“索引字段列表”中对应字段。），若需多个索引组合查询，需要在setQuery处合并，否则若设置多个setQuery子句，则后面的子句会替换前面子句
		searchParams.setQuery("default:'" + requestBo.getKeyword() + "'");
		// 设置查询过滤条件
		searchParams.setFilter("type=0"); 
		Sort sorter = new Sort();
        if(requestBo.getSortBy() == 0) {
        	if(requestBo.getSortType() == 0) {
        		sorter.addToSortFields(new SortField("price", Order.DECREASE)); //设置price字段降序
        		sorter.addToSortFields(new SortField("RANK", Order.INCREASE)); //若price相同则以RANK升序
        	}  else {
        		sorter.addToSortFields(new SortField("price", Order.INCREASE)); //设置price字段升序
        		sorter.addToSortFields(new SortField("RANK", Order.INCREASE)); //若price相同则以RANK升序
        	}
        } else {
        	if(requestBo.getSortType() == 0) {
        		sorter.addToSortFields(new SortField("totalsaleamount", Order.DECREASE)); //设置totalsaleamount字段降序
        		sorter.addToSortFields(new SortField("RANK", Order.INCREASE)); //若totalsaleamount相同则以RANK升序
        	}  else {
        		sorter.addToSortFields(new SortField("totalsaleamount", Order.INCREASE)); //设置totalsaleamount字段升序
        		sorter.addToSortFields(new SortField("RANK", Order.INCREASE)); //若totalsaleamount相同则以RANK升序
        	}
        }
        
        searchParams.setSort(sorter);

       
		
		// 执行查询语句返回数据对象
		SearchResult searchResult = null;
		try {
			searchResult = searcherClient.execute(searchParams);
		} catch (OpenSearchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OpenSearchClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 以字符串返回查询数据
		String result = searchResult.getResult();
		SearchALiResultBo skuResult = JsonUtils.jsonToBean(result, SearchALiResultBo.class);

		List<SearchResultSKUBo> bos = new ArrayList<SearchResultSKUBo>();
		if (skuResult.getResult() != null && skuResult.getResult().getTotal() > 0) {
			List<Map<String, String>> skuList = skuResult.getResult().getItems();
			for (Map<String, String> skuInfoMap : skuList) {
				SearchResultSKUBo bo = new SearchResultSKUBo();
				bo.setId(skuInfoMap.get("id"));
				bo.setShopId(skuInfoMap.get("shopid"));
				bo.setPrice(skuInfoMap.get("price"));
				bo.setPriceMarket(skuInfoMap.get("pricemarket"));
				bo.setUnit(skuInfoMap.get("unit"));
				bo.setSkuNameCn(skuInfoMap.get("skunamecn"));
				bo.setSkuTitleSub(skuInfoMap.get("skutitlesub"));
				bo.setDefaultPicURL(skuInfoMap.get("defaultpicurl"));
				bo.setTotalSaleAmount(skuInfoMap.get("totalsaleamount"));
				bos.add(bo);
			}
		}
		return bos;
	}

	private List<SearchResultSKUBo> getSkuWithoutShops(SearchRequestBo requestBo) {
		// TODO Auto-generated method stub
		return null;
	}

	private List<SearchResultShopBo> getShopResult(SearchRequestBo requestBo) {
		// 获取shop信息
		Config config = new Config(Lists.newArrayList(appName));
		config.setStart(0);
		config.setHits(5);
		// 设置返回格式为fulljson格式
		config.setSearchFormat(SearchFormat.JSON);
		// 创建参数对象
		SearchParams searchParams = new SearchParams(config);
		// 指定搜索的关键词，这里要指定在哪个索引上搜索，如果不指定的话默认在使用“default”索引（索引字段名称是您在您的数据结构中的“索引字段列表”中对应字段。），若需多个索引组合查询，需要在setQuery处合并，否则若设置多个setQuery子句，则后面的子句会替换前面子句
		searchParams.setQuery("default:'" + requestBo.getKeyword() + "'");
		// 设置查询过滤条件
		searchParams.setFilter("type=1");

		// 执行查询语句返回数据对象
		SearchResult searchResult = null;
		try {
			searchResult = searcherClient.execute(searchParams);
		} catch (OpenSearchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OpenSearchClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 以字符串返回查询数据
		String result = searchResult.getResult();
		SearchALiResultBo shopResult = null;
		try {
			 shopResult = JsonUtils.jsonToBean(result, SearchALiResultBo.class);
		} catch (Exception e) {
			System.err.println(e);
		}
		

		List<SearchResultShopBo> bos = new ArrayList<SearchResultShopBo>();
		if (shopResult.getResult() != null && shopResult.getResult().getTotal() > 0) {
			List<Map<String, String>> shopList = shopResult.getResult().getItems();
			for (Map<String, String> shopInfoMap : shopList) {
				SearchResultShopBo bo = new SearchResultShopBo();
				bo.setId(shopInfoMap.get("shopid"));
				bo.setShopAddress(shopInfoMap.get("shopaddress"));
				bo.setShopLogoUrl(shopInfoMap.get("shoplogourl"));
				bo.setShopNameCn(shopInfoMap.get("shopname"));
				bos.add(bo);
			}
		}
		return bos;
	}

}
